<?php

namespace App\Http\Controllers\School;

use App\Models\BookRule;
use App\Models\Food;
use App\Models\FoodType;
use App\Models\PriceCategory;
use App\Models\Roles;
use App\Models\UserRole;
use App\Models\Area;
use App\Models\City;
use App\Models\Province;
use App\Models\School;
use App\Models\BookOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

/**
 * Class DataController
 * @package App\Http\Controllers\School
 * @author zjw
 */
class DataController extends BaseController
{
    /**
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $sources = $request->sources;
        $data = [];
        foreach ($sources as $v) {
            if (method_exists($this, $v)) {
                $data[$v] = call_user_func([$this, $v], $request);
            }
        }
        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return Province[]|\Illuminate\Database\Eloquent\Collection
     * 地区
     */
    public function areas(Request $request)
    {
        $id = $request->get("area_id");
        if (!$id) {
            return Province::all();
        } else {
            $cities = City::where("provinceid", $id)->get();
            if (sizeof($cities) > 0) {
                return $cities;
            } else {
                return Area::where("cityid", $id)->get();
            }
        }
    }

    /**
     * @return mixed
     * 所有菜品种类
     */
    public function foodTypes()
    {
        return FoodType::orderBy('created_at', 'desc')->where('school_id', \Auth::user()->school_id)->select(['id', 'name', 'status'])->get();
    }

    /**
     * @return mixed
     * 启用的菜品
     */
    public function foods()
    {
        return Food::orderBy('created_at', 'desc')->where('school_id', \Auth::user()->school_id)->where('status', 1)->get();
    }

    /**
     * @return array
     * 存在rule_id则返回使用过的条目id, 否则返回所有启用的条目
     */
    public function categories()
    {
        return PriceCategory::orderBy('created_at', 'desc')->where('school_id', \Auth::user()->school_id)->where('status', 1)->get();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function schools(Request $request)
    {
        return School::isActive()->select(["name", 'id'])->get();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    private function userRoles(Request $request)
    {
        return UserRole::where('school_id', \Auth::user()->school_id)->get();
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function roles(Request $request)
    {
        return Role::where('guard_name', 'school')->where('school_id', \Auth::user()->school_id)->get();
    }

    /**
     * @return array
     */
    public function permissions()
    {
        $permissions = Permission::where('guard_name', 'school')->get();
        return Roles::getPermissions($permissions);
    }

    /**
     * 大屏展示信息
     * @return array
     */
    public function screenData(Request $request)
    {
        $id = $request->get("school_id");
        $today = $currentWeek = $currentMonth = 0;
        $current = [
            'breakfast' => [
                'order' => 0,
                'take' => 0,
            ],
            'lunch' => [
                'order' => 0,
                'take' => 0,
            ],
            'dinner' => [
                'order' => 0,
                'take' => 0,
            ],
        ];
        $foods = [];
        if ($id) {
            //1.用餐人数，今日，本周，本月
            $today = DB::select('select count(id) as count from book_rules where school_id=? and eat_date = ? and is_cancel=0', [$id, date('Y-m-d', time())]);
            $today = $today[0]->count;
            $currentWeek = DB::select('select count(id) as count from book_rules where school_id=? and eat_date BETWEEN ? and ? and is_cancel=0', [
                $id,
                date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"))),
                date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - date("w") + 7, date("Y")))]);
            $currentWeek = $currentWeek[0]->count;
            $currentMonth = DB::select('select count(id) as count from book_rules where school_id=? and eat_date BETWEEN ? and ? and is_cancel=0', [
                $id,
                date("Y-m-d", mktime(0, 0, 0, date("m"), 1, date("Y"))),
                date("Y-m-d", mktime(23, 59, 59, date("m"), date("t"), date("Y"))),
            ]);
            $currentMonth = $currentMonth[0]->count;
            //2.下一餐菜单
            $showDate = date("Y-m-d");
            $eatType = 2;
            //早餐 6~10  午餐 10~16:30  晚餐 17:30~22:40
            if (strtotime(date("Y-m-d 17:30:00")) <= time()) {//晚餐后显示第二天的
                $eatType = 1;
                $showDate = date("Y-m-d", time() + 24 * 60 * 60);
            } elseif (strtotime(date("Y-m-d 10:30:00")) <= time()) {//显示晚餐
                $eatType = 3;
            }
            $bookRules = BookRule::where('eat_date', $showDate)->where('eat_type', $eatType)->where('is_cancel', 0)->with('foods')->first();
            if ($bookRules && $bookRules['foods']) {
                $foods = $bookRules['foods'];
            }
            //3.早，中，晚用餐数据

            $orders = BookOrder::whereIn('book_rule_id', function ($query) use ($id) {
                $query->select('id')
                    ->from('book_rules')
                    ->where('eat_date', now()->format("Y-m-d"))->where('school_id', $id);
            })->where('status', '!=', 40)->with(['rule'])->get();
            foreach ($orders as $key => $val) {
                switch ($val->rule->eat_type) {
                    case 1:
                        $current['breakfast']['order'] += 1;
                        if ($val->status == 30) {
                            $current['breakfast']['take'] += 1;
                        }
                        break;
                    case 2:
                        $current['lunch']['order'] += 1;
                        if ($val->status == 30) {
                            $current['lunch']['take'] += 1;
                        }
                        break;
                    case 3:
                        $current['dinner']['order'] += 1;
                        if ($val->status == 30) {
                            $current['dinner']['take'] += 1;
                        }
                        break;
                    default:
                        # code...
                        break;
                }
            }
        }
        $week = array('日', '一', '二', '三', '四', '五', '六');
        return [
        	    'date' => date('Y年m月d H:i').' 星期'.$week[date("w")],
            'total' => [
                'toady' => $today, 'week' => $currentWeek, 'month' => $currentMonth
            ],
            'menu' => $foods,
            'current' => $current
        ];
    }
}
